package sms

import (
	"bytes"
	"code.google.com/p/mahonia"
	"crypto/md5"
	"encoding/hex"
	"fmt"
	"github.com/go-errors/errors"
	"github.com/gorilla/http"
	"net/url"
	"strings"
)

var (
	_url string
	_usr string
	_pwd string
)

func InitSendMsg(url, usr, pwd string) {
	_url = url
	_usr = usr
	_pwd = pwd
}

func SendMsg(phone, msg string) error {
	v := url.Values{}

	v.Add("user", _usr)
	// encode password
	h := md5.New()
	h.Write([]byte(_pwd))
	v.Add("password", hex.EncodeToString(h.Sum(nil)))
	v.Add("mobile", phone)
	// encode request to gbk
	enc := mahonia.NewEncoder("gbk")
	ret, ok := enc.ConvertStringOK(msg)
	if !ok {
		return errors.New("convert utf8 to gbk failed")
	}
	v.Add("msg", ret)
	requestUri := fmt.Sprintf("%s?%s", _url, v.Encode())

	buffer := new(bytes.Buffer)
	if code, err := http.Get(buffer, requestUri); err != nil || code == 0 {
		return err
	}

	// decode response to utf8
	dec := mahonia.NewDecoder("gbk")
	ret, ok = dec.ConvertStringOK(buffer.String())
	if !ok {
		return errors.New("convert gbk to utf8 failed")
	}
	ary := strings.Split(ret, ":")
	if len(ary) < 1 || ary[0] != "ok" {
		return errors.New("send msg failed")
	}

	return nil
}
